package com.elektronikforumet.camalert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class CameraService implements Runnable {
	
	private static final String WEBSERVICE_URL = "http://www.linushelgesson.se/SpeedCameras.asmx/GetChangedCameras";
	
	private Callback mCallback = null;
	private Date mSince = null;
	
	public CameraService(Callback callback) {
		mCallback = callback;
	}
	
	public void beginFetchChangedCameras(Date since) {
		mSince = since;
		
		Thread wsThread = new Thread(this);
		wsThread.start();		
	}
	
	public interface Callback {
		void cameraServiceReceived(ArrayList<SpeedCamera> cams);
		void cameraServiceError(String error, Throwable e);
	}

	@Override
	public void run() {
		
		if(mCallback == null) {
			mCallback.cameraServiceError("No callback class set", null);
			return;
		}
		
		ChangedCamerasParser parser = new ChangedCamerasParser();
		
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("since", DateUtils.formatDate(mSince, "yyyy-MM-dd HH:mm:ss")));
		
		DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(WEBSERVICE_URL);
        
        try {
              httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
              HttpResponse response = client.execute(httppost);
              
              HttpEntity responseEntity = response.getEntity();

              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();
              XMLReader xr = sp.getXMLReader();
              xr.setContentHandler(parser);
              xr.parse(new InputSource(responseEntity.getContent()));
              
              mCallback.cameraServiceReceived(parser.getCameras());
              
        } catch (Exception e) {
        	mCallback.cameraServiceError("WebService error", e);
        }
	}
}
